//-------------------------------------------------------------------------------------
// <copyright file="Move.cs" company="Microsoft">
//      Copyright (c) 2003 Microsoft Corporation. All rights reserved.
//      THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
//      EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
//      WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
// <summary>
//      Moves a Send Handler from one host to another.
// </summary>  
//-------------------------------------------------------------------------------------
namespace Microsoft.Sdc.Tasks.BizTalk2006.SendHandler
{
    #region Using directives
    using System;
    using System.Globalization;
    using System.Management;
    using Microsoft.Build.Framework;
    using Microsoft.Sdc.Tasks.BizTalk2004;
    using Microsoft.Sdc.Tasks.BizTalk2004.Configuration;
    #endregion

    /// <summary>
    /// Moves a SendHandler from one host to another.
    /// </summary>
    /// <remarks>
    /// <code>
    /// <![CDATA[<BizTalk2006.SendHandler.Move 
    ///                NewHostName="NewHostName"
    ///                OldHostName="OldHostName"
    ///                TransportType="FILE"
    ///                />]]>
    /// </code>
    /// <para>where:</para>
    /// <para><i>NewHostName (Required)</i></para>
    /// <para>
    /// The name of the host to move the handler too.
    /// </para>
    /// <para><i>OldHostName</i></para>
    /// <para>
    /// The name of the host that the handler is currently using. Optional, and if not
    /// provided, all hosts of the same transport type will be moved.
    /// </para>
    /// <para><i>TransportType (Required)</i></para>
    /// <para>
    /// The type of transport. E.g. FILE, SQL, SOAP. 
    /// </para>
    /// <para><i>server</i></para>
    /// <para>
    /// The logical name of the server hosting the BizTalk management database. If neither this nor the
    /// database name are specified then the installation will default to the local installation.
    /// </para>
    /// <para><i>database</i></para>
    /// <para>
    /// The name of the BizTalk management database. If neither this nor the server name are specified 
    /// then the installation will default to the local installation.
    /// </para>
    /// <para><i>username</i></para>
    /// <para>
    /// The username to use to connect to the database if using SQL Server security. The default is to
    /// connect using Windows Integrated security.
    /// </para>
    /// <para><i>password</i></para>
    /// <para>
    /// The password to use to connect to the database if using SQL Server security. The default is to
    /// connect using Windows Integrated security.
    /// </para>
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <Target Name="Test" >
    ///            <BizTalk2004.SendHandler.Move 
    ///                HostName="HostName"
    ///                TransportType="FILE"
    ///            />
    ///      </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>
    public class Move : BizTalk2004TaskBase
    {
        private string newHostName;
        private string transportType;
        private string oldHostName;

        /// <summary>
        /// The name of the host to move the handler to.
        /// </summary>
        /// <value>The name of the new host.</value>
        [Required]
        public string NewHostName
        {
            get { return this.newHostName; }
            set { this.newHostName = value; }
        }

        /// <summary>
        /// The name of the host to move the handler from.
        /// </summary>
        /// <value>The name of the old host.</value>
        public string OldHostName
        {
            get { return this.oldHostName; }
            set { this.oldHostName = value; }
        }

        /// <summary>
        /// The transport type, e.g. FILE, SQL, SOAP etc
        /// </summary>
        /// <value>The type of the transport.</value>
        [Required]
        public string TransportType
        {
            get { return this.transportType; }
            set { this.transportType = value; }
        }
        
        /// <summary>
        /// Performs the action for this task
        /// </summary>
        protected override void InternalExecute()
        {
            // getting the installation and moving the handler
            BizTalkInstallation installation = this.GetInstallation();

            if (string.IsNullOrEmpty(this.OldHostName))
            {
                this.MoveHost(installation, this.transportType, this.newHostName, string.Empty);
            }
            else
            {
                this.MoveHost(installation, this.transportType, this.newHostName, this.oldHostName);
            }
        }

        /// <summary>
        /// Moves the host.
        /// </summary>
        /// <param name="installation">The installation.</param>
        /// <param name="transportType">Type of the transport.</param>
        /// <param name="newHostName">New name of the host.</param>
        /// <param name="oldHostName">Old name of the host.</param>
        private void MoveHost(BizTalkInstallation installation, string transportType, string newHostName, string oldHostName)
        {
            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.UpdateOnly;

                // Look for the target WMI Class MSBTS_ReceiveHandler instance
                string query;
                if (string.IsNullOrEmpty(oldHostName))
                {
                    query = "SELECT * FROM MSBTS_SendHandler2 WHERE AdapterName =\"" + transportType + "\"";
                }
                else
                {
                    query = "SELECT * FROM MSBTS_SendHandler2 WHERE AdapterName =\"" + transportType + "\" AND HostName = \"" + oldHostName + "\"";
                }

                ManagementScope scope = ManagementHelper.GetManagementScope(installation);
                ManagementObjectSearcher searcherSendHandler = new ManagementObjectSearcher(scope, new WqlObjectQuery(query), null);

                if (searcherSendHandler.Get().Count > 0)
                {
                    foreach (ManagementObject objSendHandler in searcherSendHandler.Get())
                    {
                        // update host association
                        objSendHandler["HostNameToSwitchTo"] = newHostName;
                        
                        // update the ManagementObject
                        objSendHandler.Put(options);
                    }
                }
                else
                {
                    Log.LogError(string.Format(CultureInfo.InvariantCulture, "SendHandler not found: {0}", this.transportType));
                    return;
                }
            }
            catch (Exception ex)
            {
                Log.LogError(string.Format(CultureInfo.InvariantCulture, "Move SendHandler: {0} - failed {1}", this.transportType, ex.Message));
                return;
            }
        }
    }
}
        
